//电子邮件puhalskijsemen@gmail.com
//源码网站 开vpn全局模式打开 http://web3incubators.com/
//电报https://t.me/gamecode999
//网页客服 http://web3incubators.com/kefu.html

import UIGameViewUIBindings from "./UI_GameView_UIBindings";
import UIViewBase from "./UIView";
import { EventMgrInstance } from "./EventManager";
import { EVENT_TYPE } from "./EvenType";
import { Excel } from "./Excel";
import { NodePoolMag } from "./NodePoolMag";
import { BundleNames } from "./BundleConfig";
import ViewMosterLogic from "./UI_MosterLogic";
import { GameGlobalVariable } from "./GameGlobalVariable";
import ViewPlayer from "./UI_Player";
import ViewShowAttackInfo from "./UI_ShowAttackInfo";
import UIManager from "./UIManager";
import { UIView_Game } from "./UIConfig_Game";
import CommonUtils  from "./CommonUtils";
import { BuffMgr } from "./BuffMag";
import ViewBullet from "./UI_Bullet";
import { GameDataMgr } from "./GameDataManager";
import { UIView_Home } from "./UIConfig_Home";
import ViewDuWu from "./UI_DuWu";
import UI_Bag from "./UI_Bag";
import { ExcelUtil } from "./ExcelUtil";
import ViewBulletBomb from "./UI_BulletBomb";
import ViewBulletMove from "./UI_BulletMove";
import { AudioMgr } from "./AudioManager";
import { LogMgr } from "./LogManager";
import { PlayerDataMgr } from "./PlayerDataManager";
import { GameBagGuideIndex, GuideName } from "./Const_Common";
import { TipMgr } from "./TipsManager";
import ViewGameViewMap from "./UI_GameViewMap";
import ViewCreateMoster from "./UI_CreateMoster";
import UI_SkillShow from "./UI_SkillShow";
import { LoadingMgr } from "./LoadingManager";

const { ccclass, property, inspector } = cc._decorator;

/**
 * 建议类名: GameView
 */
@ccclass
export default class ViewGameView extends UIViewBase {
    @property(UIGameViewUIBindings)
    auto_ui: any = null;

    @property(cc.Node)
    UI_BagNode: cc.Node = null;

    @property(cc.Prefab)
    UI_BagPre: cc.Prefab = null;

    @property(cc.Node)
    mosterNode: cc.Node = null;

    @property(cc.Node)
    pathsNode: cc.Node = null;

    @property(cc.Node)
    playerNode: cc.Node = null;

    @property(cc.Node)
    bulletNode: cc.Node = null;

    @property(cc.Node)
    languaNode: cc.Node = null;

    @property(cc.Node)
    liulianNode: cc.Node = null;

    @property(cc.Node)
    othereff: cc.Node = null;

    @property(cc.Node)
    aixinNode: cc.Node = null;

    @property(cc.Node)
    mapNode: cc.Node = null;

    @property(cc.Node)
    tiaozhanTip: cc.Node = null;

    @property(cc.Node)
    tongjiNode: cc.Node = null;

    @property(cc.Node)
    bottmoNode: cc.Node = null;

    @property(ViewShowAttackInfo)
    showattackinfo: ViewShowAttackInfo = null;

    private bottomNd: cc.Node = null;
    private isgamepuase: boolean = true;
    private jiasuCode: number = 1;
    private isadd: boolean = false;
    private nowlevel: number = 1;
    private xueliang: number = 3;
    private fuhuocount: number = 0;
    private maxcount: number = 1;
    private isOpenPuase: boolean = false;
    private isGameOver: boolean = false;
    private overstate: number = -1;
    private addbool: boolean = false;
    private rolelevel: number = 1;
    private roleexperience: number = 0;
    private isCiTiaoOpen: boolean = false;
    private nowBag: cc.Node = null;
    private mosterScript: ViewCreateMoster = null;

    constructor() {
        super();
    }

    /**
     * 显示游戏视图
     * @param e - 参数
     * 建议方法名: showGameView
     */
    _show(e: any, ...args: any[]): void {
        const self = this;
        EventMgrInstance.emitEvent(EVENT_TYPE.Game_Load_View, false);
        this.scheduleOnce(() => { }, 3);
        console.log("登陆时间", new Date().getTime() - GameGlobalVariable.offtime);
        this.mosterScript = this.mosterNode.getComponent(ViewCreateMoster);
        this.mosterScript.setOver(this.isOver.bind(this));
        this.tiaozhanTip.active = false;
        AudioMgr.playBackgroundMusic("sound/gamebgm", true, BundleNames.Game);

        if (GameGlobalVariable.isSpecialLevel() === 1) {
            GameGlobalVariable.huanyipi = ExcelUtil.getMatchingData(
                Excel.shuiguoconfig_all,
                "configkey",
                "huanyipin"
            )[0].value;
            GameGlobalVariable.allhave = ExcelUtil.getMatchingData(
                Excel.shuiguoconfig_all,
                "configkey",
                "allhave"
            )[0].value;

            if (!GameDataMgr.getContinueChallenge()) {
                GameDataMgr.clearGameBagData();
                this.nowlevel = GameGlobalVariable.teshulevel;
                const levelData = Excel.shuiguotiaozhan(this.nowlevel);
                GameDataMgr.addSilverCoin(levelData.yinbi);
            }

            GameDataMgr.updateChallengeContinue(this.nowlevel, true);
            this.maxcount = GameGlobalVariable.wujinfuhuocount;
        } else {
            this.maxcount = GameGlobalVariable.putongfuhuocount;
            this.nowlevel = GameGlobalVariable.nowlevel;

            if (BuffMgr.ciTiaoData && BuffMgr.ciTiaoData.length > 0) {
                const gameData = GameDataMgr.getContinueGame();
                this.mosterScript.mosterboshu = gameData.nowboshu;
                GameGlobalVariable.huanyipi = GameDataMgr.getCiTiaoCount(
                    GameGlobalVariable.nowlevel,
                    1
                );
                GameGlobalVariable.allhave = GameDataMgr.getCiTiaoCount(
                    GameGlobalVariable.nowlevel,
                    2
                );

                const roleLevelData = GameDataMgr.getRoleLevel(
                    this.nowlevel,
                    GameGlobalVariable.isSpecialLevel()
                );

                if (roleLevelData) {
                    this.rolelevel = roleLevelData.level;
                    this.roleexperience = 0;
                } else {
                    this.rolelevel = 1;
                }
            } else {
                GameGlobalVariable.huanyipi = ExcelUtil.getMatchingData(
                    Excel.shuiguoconfig_all,
                    "configkey",
                    "huanyipin"
                )[0].value;
                GameGlobalVariable.allhave = ExcelUtil.getMatchingData(
                    Excel.shuiguoconfig_all,
                    "configkey",
                    "allhave"
                )[0].value;

                GameDataMgr.updateLevelWave(
                    this.nowlevel,
                    this.mosterScript.mosterboshu,
                    GameGlobalVariable.isSpecialLevel()
                );

                if (PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) === GameBagGuideIndex.GuideCompletion) {
                    GameDataMgr.clearGameBagData();
                }
            }
        }

        GameGlobalVariable.bulletNode = this.bulletNode;
        GameGlobalVariable.languaNode = this.languaNode;
        GameGlobalVariable.liulianNode = this.liulianNode;
        GameGlobalVariable.mosterNode = this.mosterNode;
        GameGlobalVariable.effNode = this.othereff;
        GameGlobalVariable.paths = this.pathsNode;
        GameGlobalVariable.nowlevelhuobi = 0;

        this.initUI();
        this.showattackinfo.addEventListener();
        this.auto_ui.dbAnim_openGame.node.active = false;

        this.scheduleOnce(() => {
            self.loadBottom();
        }, 0.5);
    }

    /**
     * 加载底部节点
     * 建议方法名: loadBottomNode
     */
    async loadBottom(): Promise<void> {
        if (!this.bottomNd) {
            const prefab = await this._loadRes(BundleNames.Game, "prefabs/bottomNode", cc.Prefab);
            this.bottomNd = cc.instantiate(prefab);
        }

        this.bottmoNode.addChild(this.bottomNd);
        this.bottomNd.setPosition(0, 0);
    }

    /**
     * 关闭视图
     * 建议方法名: closeView
     */
    _close(): void {
        super._close();
        this.showattackinfo.removeEventListener();
        BuffMgr.resetCurrentWave();
        NodePoolMag.instance.clearAllNodePools();
        cc.game.setFrameRate(60);
    }

    /**
     * 添加事件监听器
     * 建议方法名: addEventListeners
     */
    _addEventListener(): void {
        this._addEvent(EVENT_TYPE.Game_Update, this.updateMultiplier, this);
        this._addEvent(EVENT_TYPE.Game_Moster_DIE, this.onMonsterDie, this);
        this._addEvent(EVENT_TYPE.Game_Moster_Attack, this.reduceHealth, this);
        this._addEvent(EVENT_TYPE.Game_OpenGame, this.onStartGame, this);
        this._addEvent(EVENT_TYPE.Game_CreateDuWu, this.createPoisonFog, this);
        this._addEvent(EVENT_TYPE.GAME_BackHall, this.backView, this);
    }

    /**
     * 创建毒雾
     * @param e - 参数
     * @param t - 参数
     * @param o - 参数
     * 建议方法名: createPoisonFog
     */
    async createPoisonFog(e: any, t: any, o: any): Promise<void> {
        let duwuNode = NodePoolMag.instance.getNodeFromPool("duwu");

        if (!duwuNode) {
            const prefab = await this._loadRes(BundleNames.Game, "prefabs/effpre/UI_DuWu", cc.Prefab);
            NodePoolMag.instance.createNodePool("duwu", 1, prefab);
            duwuNode = NodePoolMag.instance.getNodeFromPool("duwu");
        }

        duwuNode.setPosition(e.node.x, e.node.y);
        duwuNode.angle = (e.moveindex === 1 || e.moveindex === 3 || e.moveindex === 5) ? 0 : 90;
        this.othereff.addChild(duwuNode);
        duwuNode.getComponent(ViewDuWu).initializeInfo(t, o);
    }

    /**
     * 更新倍率
     * @param e - 参数
     * 建议方法名: updateMultiplier
     */
    updateMultiplier(e: any): void {
        if (this.jiasuCode !== 1) {
            this.onUpdate(e);
        }
        this.onUpdate(e);
    }

    /**
     * 禁用时调用
     * 建议方法名: onDisable
     */
    onDisable(): void {
        GameGlobalVariable.clearAttackRecords();
    }

    /**
     * 更新
     * @param e - 参数
     * 建议方法名: update
     */
    onUpdate(e: any): void {
        if (!this.isgamepuase) {
            this.mosterScript.onCreateMonster(e);
            this.setPlayerState(e);
            this.setMonsterState(e);
            this.updateBullets(e);
            this.updateOtherEffects(e);
        }
    }

    /**
     * 更新其他效果
     * @param e - 参数
     * 建议方法名: updateOtherEffects
     */
    updateOtherEffects(e: any): void {
        this.othereff.getComponentsInChildren(ViewDuWu).forEach((duwu) => {
            duwu.onUpdate(e);
        });
    }

    /**
     * 更新子弹
     * @param e - 参数
     * 建议方法名: updateBullets
     */
    updateBullets(e: any): void {
        const self = this;

        GameGlobalVariable.bulletNode
            .getComponentsInChildren(ViewBullet)
            .forEach((bullet) => {
                bullet.onUpdate(e);
            });

        const bombComponents = GameGlobalVariable.languaNode.getComponentsInChildren(ViewBulletBomb);
        let bombCount = 0;
        const bombList: any[] = [];

        bombComponents.forEach((bomb) => {
            bomb.node.zIndex = -2;
            bombList.push(bomb);
            bomb.onUpdate(e);
            bombCount += 1;
        });

        if (bombCount > 100) {
            bombList.sort((a, b) => a.createtime - b.createtime);
            bombList.shift().hideBullet();
        }

        GameGlobalVariable.sortBlueMelons(bombList, this.mosterNode);

        bombList.forEach((bomb) => {
            bomb.getComponent(ViewBulletBomb).pengZhuangMoster(self.mosterNode);
        });

        GameGlobalVariable.liulianNode
            .getComponentsInChildren(ViewBulletMove)
            .forEach((bulletMove) => {
                bulletMove.node.zIndex = -1;
                bulletMove.onUpdate(e);
            });
    }

    /**
     * 测试打印
     * 建议方法名: testPrint
     */
    ceshiDaYin(): void { }

    /**
     * 设置玩家状态
     * @param e - 参数
     * 建议方法名: setPlayerState
     */
    setPlayerState(e: any): void {
        this.playerNode.getComponentsInChildren(ViewPlayer).forEach((player) => {
            if (player.node.active) {
                player.onUpdate(e);
            }
        });
    }

    /**
     * 设置怪物状态
     * @param e - 参数
     * 建议方法名: setMonsterState
     */
    setMonsterState(e: any): void {

        const monsterScripts = this.mosterNode.getComponentsInChildren(ViewMosterLogic);

        monsterScripts.forEach((monster) => {
            monster.onUpdate(e);
        });

        const sortedMonsters = GameGlobalVariable.sortMonsters(this.mosterNode);
        let zIndex = 999;

        sortedMonsters.forEach((monster) => {
            monster.script.node.zIndex = zIndex;
            zIndex -= 1;
        });
    }

    /**
     * 关闭
     * 建议方法名: onClose
     */
    onClose(): void { }

    /**
     * 点击监听器
     * @param e - 参数
     * 建议方法名: clickListener
     */
    _clickListener(e: cc.Button): void {
        const ui = this.auto_ui;

        switch (e) {
            case ui.btn_back:
                if (PlayerDataMgr.getGuideIndexByTaskName(GuideName.GameBag) < GameBagGuideIndex.GuideCompletion) {
                    TipMgr.showToast("请先完成引导章节挑战");
                    return;
                }
                this.onClickBack();
                break;
            case ui.btn_jiasuNode:
                this.onClickSpeed();
                break;
        }
    }

    /**
     * 重置加速
     * 建议方法名: resetSpeed
     */
    resetSpeed(): void {
        cc.director.getScheduler().setTimeScale(1);
    }

    /**
     * 设置加速状态
     * @param e - 参数
     * 建议方法名: setSpeedState
     */
    setSpeedState(e: number): void {
        this.jiasuCode = e;

        if (this.jiasuCode === 2) {
            cc.director.getScheduler().setTimeScale(2);
            this.auto_ui.btn_jiasuNode.node.children[3].active = true;
            this.auto_ui.btn_jiasuNode.node.children[2].active = false;
        } else {
            cc.director.getScheduler().setTimeScale(1);
            this.auto_ui.btn_jiasuNode.node.children[3].active = false;
            this.auto_ui.btn_jiasuNode.node.children[2].active = true;
        }
    }

    /**
     * 点击加速
     * 建议方法名: clickSpeed
     */
    onClickSpeed(): void {
        if (this.jiasuCode === 1) {
            this.setSpeedState(2);
        } else {
            this.setSpeedState(1);
        }
    }

    /**
     * 返回游戏
     * 建议方法名: backToGame
     */
    onBackToGame(): void {
        BuffMgr.cleanLiuLian();
        this.mosterScript.isCreateMoster = false;
        this.isgamepuase = true;
        this.setNodeState(2);
        EventMgrInstance.emitEvent(EVENT_TYPE.Game_CameraControl, 1);
        this.resetGame();

//         BuffMgr.cleanLiuLian();
//         this.mosterScript.isCreateMoster = false;
//         this.isgamepuase = true;
//         this.setNodeState(2);
//         EventMgrInstance.dispatchEvent(EVENT_TYPE.Game_CameraControl, 1);
//         this.resetGame();
    }

    /**
     * 重置游戏
     * 建议方法名: resetGame
     */
    resetGame(): void {
        switch (this.overstate) {
            case 1:
                this.resetSpeed();
                this.mosterScript.mosterboshu++;
                GameDataMgr.updateLevelWave(
                    this.nowlevel,
                    this.mosterScript.mosterboshu,
                    GameGlobalVariable.isSpecialLevel()
                );
                break;
            case 2:
                this.xueliang = 3;
                break;
            case 3:
                this.mosterScript.mosterboshu = 0;
                this.xueliang = 3;
                break;
        }
        this.isgamepuase = false;
        this.mosterScript.recycleMonster();
        this.updateRound();
    }

    /**
     * 开始游戏
     * 建议方法名: startGame
     */
    onStartGame(): void {
        const self = this;
        this.overstate = -1;
        this.setSpeedState(this.jiasuCode);
        this.isgamepuase = false;
        this.setNodeState(1);

        this.scheduleOnce(() => {
            EventMgrInstance.emitEvent(EVENT_TYPE.Game_CameraControl, 0.68);
        }, 0.3);

        this.scheduleOnce(() => {
            self.auto_ui.dbAnim_openGame.node.active = true;
            self.auto_ui.dbAnim_openGame.playAnimation("newAnimation", 1);
            AudioMgr.playSoundEffect("sound/pengzhuang", false, BundleNames.Game);
        }, 0.6);

        this.scheduleOnce(() => {
            self.auto_ui.dbAnim_openGame.node.active = false;
        }, 1.5);

        this.scheduleOnce(() => {
            self.playGame();
        }, 0.5);
    }

    /**
     * 挑战游戏
     * 建议方法名: challengeGame
     */
    challengeGame(): void {
        this.overstate = -1;
        this.setSpeedState(this.jiasuCode);
        this.isgamepuase = false;
        this.playGame();
    }

    /**
     * 设置节点状态
     * @param e - 参数
     * 建议方法名: setNodeState
     */
    setNodeState(e: number): void {
        const self = this;

        switch (e) {
            case 1:
                this.scheduleOnce(() => {
                    self.UI_BagNode.active = false;
                    self.mapNode.y = 0;
                    self.mapNode.opacity = 255;
                    self.updateRound();
                }, 0.3);

                this.auto_ui.node_shuimitao.active = true;
                this.auto_ui.node_shuimitao.opacity = 0;
                cc.Tween.stopAllByTarget(this.auto_ui.node_shuimitao);
                cc.tween(this.auto_ui.node_shuimitao).to(0.5, { opacity: 255 }).start();

                this.auto_ui.node_chaoxue.active = true;
                this.auto_ui.node_chaoxue.opacity = 0;
                cc.tween(this.auto_ui.node_chaoxue).to(0.5, { opacity: 255 }).start();

                this.auto_ui.btn_jiasuNode.node.active = true;
                this.auto_ui.btn_jiasuNode.node.opacity = 0;
                cc.tween(this.auto_ui.btn_jiasuNode.node).to(0.5, { opacity: 255 }).start();

                this.aixinNode.active = true;
                this.aixinNode.opacity = 0;
                cc.tween(this.aixinNode).to(0.5, { opacity: 255 }).start();

                this.auto_ui.node_lu.active = true;
                this.auto_ui.node_lu.opacity = 0;
                cc.tween(this.auto_ui.node_lu).to(0.5, { opacity: 255 }).start();

                this.tongjiNode.active = true;
                this.tongjiNode.opacity = 0;
                cc.tween(this.tongjiNode).to(0.5, { opacity: 255 }).start();

                this.playerNode.active = true;
                this.playerNode.opacity = 0;
                cc.tween(this.playerNode).to(0.5, { opacity: 255 }).start();

                cc.game.setFrameRate(59);
                break;

            case 2:
                EventMgrInstance.emitEvent(EVENT_TYPE.GAME_HIDE_TONGJI);
                cc.tween(this.mapNode).to(0.5, { y: 100 }).start();
                cc.tween(this.playerNode).to(0.5, { y: 100 }).start();

                this.scheduleOnce(() => {
                    self.mapNode.getComponent(ViewGameViewMap).recycleNodes();
                    self.mapNode.opacity = 0;
                    self.mapNode.y = 0;
                    self.playerNode.y = 0;
                    self.playerNode.active = false;
                    self.UI_BagNode.active = true;
                    self.UI_BagNode.children[0].getComponent(UI_Bag).openView({ isGameEnd: true });
                    self.updateRound();
                }, 0.6);

                cc.Tween.stopAllByTarget(this.auto_ui.node_shuimitao);
                cc.tween(this.auto_ui.node_shuimitao).to(0.5, { opacity: 0 }).call(() => {
                    self.auto_ui.node_shuimitao.active = false;
                }).start();

                cc.tween(this.auto_ui.node_chaoxue).to(0.5, { opacity: 0 }).call(() => {
                    self.auto_ui.node_chaoxue.active = false;
                }).start();

                cc.tween(this.auto_ui.btn_jiasuNode.node).to(0.5, { opacity: 0 }).call(() => {
                    self.auto_ui.btn_jiasuNode.node.active = false;
                }).start();

                cc.tween(this.aixinNode).to(0.5, { opacity: 0 }).call(() => {
                    self.aixinNode.active = false;
                }).start();

                cc.tween(this.auto_ui.node_lu).to(0.5, { opacity: 0 }).call(() => {
                    self.auto_ui.node_lu.active = false;
                }).start();

                cc.game.setFrameRate(60);

                if (cc.winSize.height / cc.winSize.width < 2) {
                    cc.tween(this.tongjiNode).to(0.5, { opacity: 0 }).call(() => {
                        self.tongjiNode.active = false;
                    }).start();
                }
                break;
        }
    }

    /**
     * 开始游戏
     * 建议方法名: playGame
     */
    playGame(): void {
        this.mosterScript.initMoster();
        this.updateExperienceUI();
        this.updateHealth();
    }

    /**
     * 减血
     * @param e - 参数
     * 建议方法名: reduceHealth
     */
    reduceHealth(e: any): void {
        const monsterId = e.mosterId;
        let damage = 1;

        if (Excel.shuiguoguaiwu(monsterId).boss === 1) {
            damage = 3;
        }

        EventMgrInstance.emitEvent(EVENT_TYPE.COMMON_SHAK);
        this.xueliang -= damage;

        if (this.xueliang < 0) {
            this.xueliang = 0;
        }

        AudioMgr.playSoundEffect("sound/abb", false, BundleNames.Game);
        this.updateHealth();

        if (this.xueliang <= 0) {
            this.mosterScript.isCreateMoster = false;
            this.isgamepuase = true;
            this.resetSpeed();

            if (this.fuhuocount < this.maxcount) {
                this.fuhuocount += 1;
                if (GameGlobalVariable.isSpecialLevel() === 1) {
                    BuffMgr.clearCurrentCiTiao();
                }
                UIManager.open(BundleNames.Game, UIView_Game.UI_GameFail, {
                    back: this.onBack.bind(this),
                    type: GameGlobalVariable.isSpecialLevel()
                });
            } else {
                this.onBack(4);
            }
        }

//         const monsterId = e.mosterId;
//         let damage = 1;

//         if (Excel.shuiguoguaiwu(monsterId).boss === 1) {
//             damage = 3;
//         }

//         EventMgrInstance.dispatchEvent(EVENT_TYPE.COMMON_SHAK);
//         this.xueliang -= damage;
//         // mg.vibrateShort();

//         if (this.xueliang < 0) {
//             this.xueliang = 0;
//         }

//         AudioMgr.playEffect("sound/abb", false, BundleNames.Game);
//         this.updateXue();

//         if (this.xueliang <= 0) {
//             this.mosterScript.isCreateMoster = false;
//             this.isgamepuase = true;
//             this.resetJiaShu();

//             if (this.fuhuocount < this.maxcount) {
//                 this.fuhuocount += 1;
//                 if (GameGlobalVariable.isTeShuLevel() === 1) {
//                     BuffMgr.cleanNowCiTiao();
//                 }
//                 UIManager.open(BundleNames.Game, UIView_Game.UI_GameFail, {
//                     back: this.onBack.bind(this),
//                     type: GameGlobalVariable.isTeShuLevel()
//                 });
//             } else {
//                 this.onBack(4);
//             }
//         }
    }

    /**
     * 更新血量
     * 建议方法名: updateHealth
     */
    updateHealth(): void {
        const hearts = this.aixinNode.children;

        for (let i = 0; i < hearts.length; i++) {
            const heart = hearts[i];
            heart.children[0].active = this.xueliang >= i + 1;
        }
    }

    /**
     * 显示图鉴
     * 建议方法名: showIllustration
     */
    showIllustration(): void {
        UIManager.open(BundleNames.Game, UIView_Game.UI_TuJian);
    }

    /**
     * 更新轮数
     * 建议方法名: updateRound
     */
    updateRound(): void {
        let levelData;

        if (GameGlobalVariable.isSpecialLevel() === 1) {
            levelData = Excel.shuiguotiaozhan(this.nowlevel);
        } else {
            levelData = Excel.shuiguoguanqia(this.nowlevel);
        }

        const currentWave = this.mosterScript.getCurrentWave();

        if (this.UI_BagNode.active && GameGlobalVariable.isSpecialLevel() === 1) {
            this.auto_ui.txt_lunhui.string = "一波合成,怪物无尽来袭";
        } else {
            this.auto_ui.txt_lunhui.string = `第${currentWave}/${levelData.levelboshuid.length}波`;
        }
    }

    /**
     * 返回
     * @param e - 参数
     * 建议方法名: back
     */
    onBack(e: number): void {
        switch (e) {
            case 1:
                if (GameGlobalVariable.isSpecialLevel() === 1) {
                    EventMgrInstance.emitEvent(EVENT_TYPE.Game_Add_YinBi, 30);
                } else {
                    EventMgrInstance.emitEvent(EVENT_TYPE.Game_Add_YinBi, 15);
                }
                this.overstate = 2;
                this.onBackToGame();
                break;
            case 2:
                this.overstate = 3;
                this.resetGame();
                BuffMgr.clearCurrentCiTiao();
                this.backView();
                GameDataMgr.clearGameBagData();
                EventMgrInstance.emitEvent(EVENT_TYPE.Game_Hide);
                EventMgrInstance.emitEvent(EVENT_TYPE.Game_CameraControl, 1);
                break;
            case 3:
                this.setSpeedState(this.jiasuCode);
                if (!this.isCiTiaoOpen && !this.isOpenPuase) {
                    this.isgamepuase = false;
                }
                break;
            case 4:
                this.isGameOver = true;
                UIManager.open(BundleNames.Game, UIView_Game.UI_GameOver, {
                    type: 1,
                    back: this.onBack.bind(this)
                });
                break;
        }

//         switch (e) {
//             case 1:
//                 if (GameGlobalVariable.isTeShuLevel() === 1) {
//                     EventMgrInstance.dispatchEvent(EVENT_TYPE.Game_Add_YinBi, 30);
//                 } else {
//                     EventMgrInstance.dispatchEvent(EVENT_TYPE.Game_Add_YinBi, 15);
//                 }
//                 this.overstate = 2;
//                 this.onBackGame();
//                 break;
//             case 2:
//                 this.overstate = 3;
//                 this.resetGame();
//                 BuffMgr.cleanNowCiTiao();
//                 this.backView();
//                 GameDataMgr.ClearGameBagData();
//                 EventMgrInstance.dispatchEvent(EVENT_TYPE.Game_Hide);
//                 EventMgrInstance.dispatchEvent(EVENT_TYPE.Game_CameraControl, 1);
//                 break;
//             case 3:
//                 this.setJiaShuState(this.jiasuCode);
//                 if (!this.isCiTiaoOpen && !this.isOpenPuase) {
//                     this.isgamepuase = false;
//                 }
//                 break;
//             case 4:
//                 this.isGameOver = true;
//                 UIManager.open(BundleNames.Game, UIView_Game.UI_GameOver, {
//                     type: 1,
//                     back: this.onBack.bind(this)
//                 });
//                 break;
//         }
    }

    /**
     * 点击返回
     * 建议方法名: clickBack
     */
    onClickBack(): void {
        const self = this;
        this.resetSpeed();
        this.isgamepuase = true;
        this.isOpenPuase = true;

        UIManager.open(BundleNames.Game, UIView_Game.UI_GamePuase, {
            back: (t: number) => {
                self.isOpenPuase = false;
                self.onBack(t);
            }
        });
    }

    /**
     * 返回视图
     * 建议方法名: backView
     */
    backView(): void {
        GameDataMgr.updateChallengeContinue(this.nowlevel, false);
        this.resetSpeed();
        EventMgrInstance.emitEvent(EVENT_TYPE.Game_Load_View, true);
        this.onHideView();
        UIManager.closeAllViews();
        UIManager.open(
            BundleNames.Home,
            UIView_Home.UI_Hall,
            GameGlobalVariable.isSpecialLevel()
        );
    }

    /**
     * 隐藏视图
     * 建议方法名: hideView
     */
    onHideView(): void {
        this._close();
    }

    /**
     * 判断游戏是否通过
     * 建议方法名: isGamePassed
     */
    isGamePassed(): boolean {
        const levelData = GameGlobalVariable.isSpecialLevel() === 1
            ? Excel.shuiguotiaozhan(this.nowlevel)
            : Excel.shuiguoguanqia(this.nowlevel);

        const nextWave = this.mosterScript.mosterboshu + 1;

        if (levelData.levelboshuid[nextWave]) {
            return true;
        } else {
            GameDataMgr.updateLevelWave(
                this.nowlevel,
                nextWave,
                GameGlobalVariable.isSpecialLevel()
            );
            this.isGameOver = true;
            this.mosterScript.isCreateMoster = false;
            this.isgamepuase = true;
            this.resetSpeed();

            if (!this.isCiTiaoOpen) {
                EventMgrInstance.emitEvent(EVENT_TYPE.Game_Hide);
                console.log("挑战模式通关");
                UIManager.open(BundleNames.Game, UIView_Game.UI_GameOver, {
                    type: 2,
                    back: this.onBack.bind(this)
                });
            }

            return false;
        }
    }

    /**
     * 回收子弹
     * 建议方法名: recycleBullets
     */
    recycleBullets(): void {
        const bullets = this.bulletNode.children;
        const bulletCount = bullets.length;

        for (let i = 0; i < bulletCount; i++) {
            const bulletNode = bullets[0];
            const bulletComponent = bulletNode.getComponent(ViewBullet);

            if (bulletComponent) {
                NodePoolMag.instance.recycleNodeToPool("bullet_" + bulletComponent.bulletId, bulletNode);
            }
        }

        const liulianBullets = GameGlobalVariable.liulianNode.children;
        const liulianBulletCount = liulianBullets.length;

        for (let i = 0; i < liulianBulletCount; i++) {
            const liulianBulletNode = liulianBullets[0];
            const liulianBulletComponent = liulianBulletNode.getComponent(ViewBulletMove);
            NodePoolMag.instance.recycleNodeToPool("bullet_" + liulianBulletComponent.bulletId, liulianBulletNode);
        }
    }

    /**
     * 判断是否结束
     * 建议方法名: isOver
     */
    isOver(): void {
        const self = this;

        if (this.mosterNode.children.length <= 0) {
            LogMgr.debug("当前一轮通关 进入合成界面");

            if (this.overstate === -1) {
                EventMgrInstance.emitEvent(EVENT_TYPE.GAME_LOCK_SCREE, true);

                if (this.isGamePassed()) {
                    BuffMgr.saveCurrentCiTiao();
                    BuffMgr.boshuAttackAdd();

                    if (GameGlobalVariable.isSpecialLevel() === 1) {
                        this.overstate = 1;
                        this.recycleBullets();
                        BuffMgr.cleanLiuLian();
                        this.mosterScript.mosterboshu += 1;
                        GameDataMgr.updateLevelWave(
                            this.nowlevel,
                            this.mosterScript.mosterboshu,
                            GameGlobalVariable.isSpecialLevel()
                        );
                        this.mosterScript.recycleMonster();
                        this.updateRound();
                        this.tiaozhanTip.active = true;
                        this.tiaozhanTip.opacity = 255;
                        this.tiaozhanTip.scaleY = 0;
                        this.tiaozhanTip.children[1].getComponent(cc.Label).string =
                            `第${this.mosterScript.mosterboshu}波结束,进入第${this.mosterScript.mosterboshu + 1}波`;
                        this.challengeGame();

                        cc.tween(this.tiaozhanTip)
                            .to(0.5, { scaleY: 1 })
                            .delay(0.5)
                            .call(() => {
                                EventMgrInstance.emitEvent(EVENT_TYPE.GAME_LOCK_SCREE, false);
                            })
                            .to(0.25, { opacity: 0 })
                            .call(() => { })
                            .start();
                    } else {
                        AudioMgr.playSoundEffect("sound/boxopen", false, BundleNames.Game);
                        this.auto_ui.node_playani.active = true;
                        this.auto_ui.node_playani.getComponent(dragonBones.ArmatureDisplay).playAnimation("box", 1);

                        this.scheduleOnce(() => {
                            const levelData = Excel.shuiguoguanqia(GameGlobalVariable.nowlevel);
                            const reward = BuffMgr.calculateFinalAward(levelData.yinbi);
                            EventMgrInstance.emitEvent(EVENT_TYPE.Game_Add_YinBi, reward);
                            self.overstate = 1;

                            self.scheduleOnce(() => {
                                self.auto_ui.node_playani.active = false;
                                self.onBackToGame();
                                EventMgrInstance.emitEvent(EVENT_TYPE.Game_Hide);
                                EventMgrInstance.emitEvent(EVENT_TYPE.Game_CameraControl, 1);
                            }, 2);
                        }, 0.6);
                    }
                }
            }
        }
    }

    /**
     * 怪物死亡
     * @param e - 参数
     * 建议方法名: onMonsterDie
     */
    onMonsterDie(e: any): void {
        const monsterId = e.moster;
        let experience = Excel.shuiguoguaiwu(monsterId).mosterjinyan;
        experience = BuffMgr.getPlayerExperienceValue(experience);
        this.roleexperience += experience;
        this.updateExperienceUI();
    }

    /**
     * 更新经验UI
     * 建议方法名: updateExperienceUI
     */
    updateExperienceUI(): void {
        const self = this;

        if (!this.isCiTiaoOpen && !this.isGameOver) {
            const levelData = Excel.shuiguoneibulevel(this.rolelevel);
            console.log("当前获得经验变化", this.roleexperience, levelData.jinyan);

            if (this.roleexperience >= levelData.jinyan) {
                this.isCiTiaoOpen = true;
                this.isgamepuase = true;
                this.roleexperience -= levelData.jinyan;
                console.log("剩余经验", this.roleexperience);
                this.rolelevel += 1;

                this.scheduleOnce(() => {
                    self.resetSpeed();
                    UIManager.open(BundleNames.Game, UIView_Game.UI_ChiTiao, {
                        back: self.backToCiTiao.bind(self),
                        nowbo: self.mosterScript.getCurrentWave()
                    });
                }, 0.2);
            }

            if (this.bottomNd) {
                const skillShowComponent = this.bottomNd.getComponent(UI_SkillShow);
                const experienceRatio = this.roleexperience / levelData.jinyan;
                skillShowComponent.updateUI(this.rolelevel, experienceRatio);
            }

            GameDataMgr.updateRoleLevel(
                this.nowlevel,
                this.rolelevel,
                this.roleexperience,
                GameGlobalVariable.isSpecialLevel()
            );
        }
    }

    /**
     * 返回词条
     * 建议方法名: backToCiTiao
     */
    backToCiTiao(): void {
        this.setSpeedState(this.jiasuCode);
        this.isCiTiaoOpen = false;

        if (!this.isCiTiaoOpen && !this.isOpenPuase) {
            this.isgamepuase = false;
        }

        this.updateExperienceUI();
    }

    /**
     * 初始化UI
     * 建议方法名: initializeUI
     */
    async initUI(): Promise<void> {
        let levelData = null;

        if (GameGlobalVariable.isSpecialLevel() === 1) {
            levelData = Excel.shuiguotiaozhan(this.nowlevel);
        } else {
            levelData = Excel.shuiguoguanqia(this.nowlevel);
        }

        const startTime = new Date().getTime();
        const bgSprite = this.auto_ui.node_bg.getComponent(cc.Sprite);
        const chaoxueSprite = this.auto_ui.node_chaoxue.getComponent(cc.Sprite);
        const luSprite = this.auto_ui.node_lu.getComponent(cc.Sprite);

        const bgSpriteFrame = await this._loadRes(
            BundleNames.Game,
            `res/bg/changjin/场景${levelData.dipicture}`,
            cc.SpriteFrame
        );
        bgSprite.spriteFrame = bgSpriteFrame;

        const chaoxuePositions = [
            { x: -63.189, y: 529.428 },
            { x: -63.189, y: 529.428 },
            { x: -38.237, y: 560.618 },
            { x: -61.717, y: 536.019 }
        ];

        const chaoxueSpriteFrame = await this._loadRes(
            BundleNames.Game,
            `res/bg/caoxue${levelData.dipicture}`,
            cc.SpriteFrame
        );
        chaoxueSprite.spriteFrame = chaoxueSpriteFrame;
        chaoxueSprite.node.setPosition(chaoxuePositions[levelData.dipicture - 1]);

        const luSpriteFrame = await this._loadRes(
            BundleNames.Game,
            `res/bg/lu${levelData.dipicture}`,
            cc.SpriteFrame
        );
        luSprite.spriteFrame = luSpriteFrame;

        console.log("背景底图时间差", new Date().getTime() - startTime);

        this.loadUIBag();

        if (GameGlobalVariable.isSpecialLevel() === 1) {
            this.auto_ui.txt_level.string = "无尽试炼";
        } else {
            this.auto_ui.txt_level.string = `第${this.nowlevel}章`;
        }

        if (cc.winSize.height / cc.winSize.width < 2) {
            this.tongjiNode.active = false;
        } else {
            this.tongjiNode.active = true;
        }

        this.updateRound();
        this.setSpeedState(1);
    }

    /**
     * 加载UI包
     * 建议方法名: loadUiBag
     */
    async loadUIBag(): Promise<void> {
        LoadingMgr.show();

        if (!this.nowBag) {
            const prefab = await this._loadRes(BundleNames.Game, "prefabs/hecheng/UI_Bag", cc.Prefab);
            this.nowBag = cc.instantiate(prefab);
        }

        this.UI_BagNode.addChild(this.nowBag);
        LoadingMgr.hide();
    }

    /**
     * 点击通关
     * 建议方法名: clickPass
     */
    onClickTongGuan(): void {
        this.overstate = 1;
        let levelData;

        if (GameGlobalVariable.isSpecialLevel() === 1) {
            levelData = Excel.shuiguotiaozhan(this.nowlevel);
        } else {
            levelData = Excel.shuiguoguanqia(this.nowlevel);
        }

        this.mosterScript.mosterboshu = levelData.levelboshuid.length;
        this.isGamePassed();
    }

    /**
     * 点击词条
     * 建议方法名: clickCiTiao
     */
    onClickCiTiao(): void {
        UIManager.open(BundleNames.Game, UIView_Game.UI_ChiTiao, {
            back: this.backToCiTiao.bind(this)
        });
    }

    /**
     * 设置词条内容
     * @param e - 参数
     * 建议方法名: setCiTiaoContent
     */
    setCiTiaoContent(e: any): string {
        const description = e.citiaomiaoshu;
        const buffData = Excel.shuiguobuff(e.citiaoshuzhitype);
        const values = buffData.value.map((val: any) => val.toString());
        return CommonUtils.replaceStringSymbols(description, "X", values);
    }
}

